package com.zoro.dyformservice.support.web.converter;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.zoro.dyformservice.interfaces.CodeData;
import com.zoro.dyformservice.utils.StringUtils;

import java.io.IOException;

/**
 * @author zhaoxingwu
 */
public class CodeDataDeserializer<T extends CodeData> extends JsonDeserializer<T> {


    private final T[] enums;

    public CodeDataDeserializer(Class<T> enumClass) {
        if (enumClass == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        if (!enumClass.isEnum()) {
            throw new IllegalArgumentException(enumClass.getName() + "is not a enum");
        }
        this.enums = enumClass.getEnumConstants();
    }

    @Override
    public T deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String text = jsonParser.getText();
        if (StringUtils.isBlank(text)) {
            return null;
        }
        for (T e : enums) {
            if (text.equals(e.getCode())) {
                return e;
            }
        }
        return null;
    }
}
